﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;
using LibraryMusicStore;
using MvcMusicStore.ViewModels;

namespace MvcMusicStore.Controllers
{
    public class HomeController : Controller
    {
        MusicStoreEntities storeDB = new MusicStoreEntities(); 
        //
        // GET: /Home/

        //public HomeController()
        //{
        //    var vat = storeDB.VATs.First(v => v.VATId == 1);
        //    ViewData["vat"] = vat.Value/100;
        //}

        [HttpGet]
        public ActionResult Index()
        {
            try
            {
                //get most popular albums
                var albums = GetTopSellingAlbums(5);
                ViewData["vat"] = 1 + storeDB.VATs.First().Value / 100;

                return View(albums);
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
            
        }
        
        private List<Album> GetTopSellingAlbums(int count)
        {
            //group the order details by album and
            //return the albums with the highest count
            return storeDB.Albums
                .Where(a => a.Deleted == false || a.Deleted == null)
                .OrderByDescending(a => a.OrderDetails.Sum(o => o.Quantity))
                .Take(count)
                .ToList();
        }

        [HttpPost]
        public ActionResult Search(string searchTerm)
        {
            try
            {
                if (searchTerm == string.Empty)
                    return View("NoItems");
                else
                {
                    // if the search contains only one result return details
                    // otherwise a list
                    var albums = storeDB.Albums
                        .Where(a => (a.Deleted == false || a.Deleted == null)
                            && a.Title.Contains(searchTerm))
                        .OrderBy(a => a.Title);

                    //from a in storeDB.Albums
                    //     where a.Title.Contains(searchTerm)
                    //     orderby a.Title
                    //     select a;

                    if (albums.Count() == 0)
                        return View("NotFound");

                    ViewData["vat"] = 1 + storeDB.VATs.First().Value / 100;

                    if (albums.Count() > 1)
                        return View("List", albums);
                    else
                        return RedirectToAction("Details", "Store", new { id = albums.First().AlbumId });
                }
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
            
        }

        [HttpGet, ChildActionOnly]
        public ActionResult SearchAdvance(int? genreId) //selected genreid
        {
            try
            {
                var viewModel = new SearchViewModel
                {
                    Genres = storeDB.Genres.ToList(),
                    Artists = storeDB.Artists.ToList()
                };

                viewModel.Genres.Insert(0, new Genre
                {
                    GenreId = 0,
                    Name = "Tất cả loại",
                });

                viewModel.Artists.Insert(0, new Artist
                {
                    ArtistId = 0,
                    Name = "Tất cả nghệ sĩ"
                });

                string[] priceFrom = { "Giá từ", "1", "2", "4", "6", "8", "12", "14", "20", "30", "40", "50" };
                string[] priceTo = { "Giá đến", "3", "5", "7", "9", "11", "13", "15", "25", "35", "45", "100" };

                viewModel.PriceFrom = new List<string>(priceFrom);
                viewModel.PriceTo = new List<string>(priceTo);

                return PartialView("../Shared/SearchAdvance", viewModel);
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        [HttpPost]
        public ActionResult SearchAdvance(string searchTerm,
            int? genreID, int? artistId, string priceFrom, string priceTo)
        {
            try
            {
                if (this.ControllerContext.IsChildAction)
                    return SearchAdvance(null);//Get action method <important>

                if (searchTerm == "Từ khóa" && genreID == 0
                    && artistId == 0 && priceFrom == "Giá từ" && priceTo == "Giá đến")
                {
                    return View("NoItems");
                }

                ViewData["vat"] = 1 + storeDB.VATs.First().Value / 100;

                IEnumerable<Album> albums;

                if (genreID == 0 && artistId == 0)
                    albums = storeDB.Albums;
                else if (genreID == 0)
                    albums = storeDB.Albums.Where(a =>
                        a.ArtistId == artistId);
                else if (artistId == 0)
                    albums = storeDB.Albums.Where(a =>
                        a.GenreId == genreID);
                else
                    albums = storeDB.Albums.Where(a =>
                        a.GenreId == genreID &&
                        a.ArtistId == artistId);

                if (priceTo != "Giá đến" && priceFrom != "Giá từ")
                    albums = albums.Where(a =>
                        a.Price * Convert.ToDecimal(ViewData["vat"]) <= Convert.ToDecimal(priceTo) &&
                        a.Price * Convert.ToDecimal(ViewData["vat"]) >= Convert.ToDecimal(priceFrom));
                else if (priceTo != "Giá đến")
                    albums = albums.Where(a =>
                            a.Price * Convert.ToDecimal(ViewData["vat"]) <= Convert.ToDecimal(priceTo));
                else if (priceFrom != "Giá từ")
                    albums = albums.Where(a =>
                            a.Price * Convert.ToDecimal(ViewData["vat"]) >= Convert.ToDecimal(priceFrom));

                if (searchTerm != "Từ khóa")
                {
                    albums = from a in albums
                             where a.Title.Contains(searchTerm)
                             //orderby a.Price
                             select a;
                }

                albums = albums
                    .Where(a => a.Deleted == false || a.Deleted == null)
                    .OrderBy(a => a.Price);

                if (albums.Count() == 0)
                    return View("NotFound");

                if (albums.Count() > 1)
                    return View("List", albums);
                else
                    return RedirectToAction("Details", "Store", new { id = albums.First().AlbumId });
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }
    }
}
